package com.binc.testspring.encode;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * FileName: MemoryEncoding
 * Autho: binC
 * Date:  2022/3/10 15:00
 */
public class MemoryEncoding {

    public static void main(String[] args) throws UnsupportedEncodingException {
        //1、String 类提供字符串转换到字节的方法，也支持将字节转换成字符串的构造函数。

        String s  = "字符串";
        byte[] b = s.getBytes("UTF-8");
        String n = new String(b, "UTF-8");
        System.out.println(Arrays.toString(b));  //[-27, -83, -105, -25, -84, -90, -28, -72, -78]
        System.out.println(n);

        System.out.println("---------");
        //2 Charset 提供 encode 与 decode，分别对应 char[] 到 byte[] 的编码 和 byte[] 到 char[] 的解码。

        Charset charset = Charset.forName("UTF-8");
        ByteBuffer byteBuffer = charset.encode(s);
        CharBuffer charBuffer = charset.decode(byteBuffer);
        System.out.println(Arrays.toString(byteBuffer.array())); //[-27, -83, -105, -25, -84, -90, -28, -72, -78, 0, 0, 0, 0, 0, 0]
        // System.out.println(byteBuffer);
        System.out.println(charBuffer);
    }
}
